package cn.siat.gene.controller;

import cn.hutool.core.convert.Convert;
import cn.siat.common.core.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.siat.common.core.web.controller.BaseController;
import cn.siat.common.core.web.domain.AjaxResult;
import cn.siat.common.core.web.page.TableDataInfo;
import cn.siat.common.log.annotation.Log;
import cn.siat.common.log.enums.BusinessType;
import cn.siat.common.security.annotation.RequiresPermissions;
import cn.siat.common.security.utils.SecurityUtils;
import cn.siat.gene.domain.ModelInfo;
import cn.siat.gene.service.IModelInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description: 模型信息
 * @Author: Administrator
 * @Date: 2022-10-22
 * @Version: V1.0
 */
@Api(tags = "模型信息")
@RestController
@RequestMapping("/model")
@Slf4j
public class ModelInfoController extends BaseController {
    @Autowired
    private IModelInfoService modelInfoService;

    /**
     * 分页列表查询
     *
     * @param modelInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "模型信息-分页列表查询", notes = "模型信息-分页列表查询")
    @RequiresPermissions("system:modelInfo:list")
    @GetMapping(value = "/list/page")
    public TableDataInfo queryPageList(ModelInfo modelInfo,
                                       @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
        startPage();
        QueryWrapper<ModelInfo> queryWrapper = new QueryWrapper<>();
        QueryWrapper<ModelInfo> wrapper = new QueryWrapper<>();
        String modelName = modelInfo.getModelName();
        String startDate = modelInfo.getStartDate();
        String endDate = modelInfo.getEndDate();
        Integer[] states = Convert.toIntArray(modelInfo.getStates());
        if(modelName != null && StringUtils.hasLength(modelName)){
            queryWrapper.like("model_name",modelName.trim());
            wrapper.like("model_name",modelName.trim());
        }
        if(startDate != null && endDate != null){
            queryWrapper.apply("to_date(cast(update_time as TEXT),'YYYY-MM-DD HH24:MI:SS')" +
                    " BETWEEN " +
                    "to_date(cast('"+startDate+"' as TEXT),'YYYY-MM-DD HH24:MI:SS')" +
                    " AND " +
                    "to_date(cast('"+endDate+"' as TEXT),'YYYY-MM-DD HH24:MI:SS')");
            wrapper.apply("to_date(cast(update_time as TEXT),'YYYY-MM-DD HH24:MI:SS')" +
                    " BETWEEN " +
                    "to_date(cast('"+startDate+"' as TEXT),'YYYY-MM-DD HH24:MI:SS')" +
                    " AND " +
                    "to_date(cast('"+endDate+"' as TEXT),'YYYY-MM-DD HH24:MI:SS')");
        }
        if(states != null && states.length >= 1){
            queryWrapper.in("model_state", Arrays.asList(states));
            wrapper.in("model_state", Arrays.asList(states));
        }
        queryWrapper.eq("is_delete", 1).eq("is_read",0);
        queryWrapper.orderByDesc("update_time");
        List<ModelInfo> list = modelInfoService.list(queryWrapper);
        List<ModelInfo> defaultList = modelInfoService.list(wrapper.
                eq("is_read",1).eq("is_delete", 1).orderByDesc("update_time"));
        defaultList.addAll(list);
        return getDataTable(defaultList);
    }

    /**
     * 查询全部数据
     *
     * @return
     */
    @ApiOperation(value = "模型信息-查询全部数据", notes = "模型信息-查询全部数据")
    @RequiresPermissions("system:modelInfo:list")
    @GetMapping(value = "/list")
    public AjaxResult queryList() {
        QueryWrapper<ModelInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 1).eq("model_state",1); // 查询有效数据
        return AjaxResult.success(modelInfoService.list(queryWrapper));
    }

    /**
     * 添加
     *
     * @param modelInfo
     * @return
     */
    @Log(title = "模型信息-添加", businessType = BusinessType.INSERT)
    @ApiOperation(value = "模型信息-添加", notes = "模型信息-添加")
    @RequiresPermissions("system:modelInfo:add")
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody ModelInfo modelInfo) {
        modelInfo.setIsDelete(1);
        modelInfo.setIsRead(0);
        modelInfo.setCreateTime(new Date());
        modelInfo.setUpdateTime(new Date());
        modelInfo.setCreateStaffNo(SecurityUtils.getUserId());
        modelInfo.setUpdateStaffNo(SecurityUtils.getUserId());
        modelInfoService.save(modelInfo);
        return AjaxResult.success("操作成功");
    }

    /**
     * 编辑
     *
     * @param modelInfo
     * @return
     */
    @Log(title = "模型信息-编辑", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "模型信息-编辑", notes = "模型信息-编辑")
    @RequiresPermissions("system:modelInfo:edit")
    @PutMapping(value = "/edit")
    public AjaxResult edit(@RequestBody ModelInfo modelInfo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("number", modelInfo.getNumber());
        queryWrapper.ne("id", modelInfo.getId());
        if (modelInfoService.count(queryWrapper) > 0) {
            return AjaxResult.error("模型编码已存在");
        }

        modelInfo.setUpdateStaffNo(SecurityUtils.getUserId());
        modelInfo.setUpdateTime(new Date());
        modelInfoService.updateById(modelInfo);
        return AjaxResult.success("操作成功");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Log(title = "模型信息-通过id删除", businessType = BusinessType.DELETE)
    @ApiOperation(value = "模型信息-通过id删除", notes = "模型信息-通过id删除")
    @RequiresPermissions("system:modelInfo:remove")
    @DeleteMapping(value = "/delete")
    public AjaxResult delete(@RequestParam(name = "id", required = true) String id) {
        ModelInfo data = modelInfoService.getById(id);
        if(data == null){
            throw new ServiceException("删除模型信息不存在！");
        }
        if (data.getIsDelete()==0){
            throw new ServiceException("模型信息已被删除！");
        }
        if (data != null) {
            data.setIsDelete(0);
            data.setUpdateStaffNo(SecurityUtils.getUserId());
            data.setUpdateTime(new Date());
            modelInfoService.updateById(data);
        }

        return toAjax(true);
    }

    /**
     * 批量删除
     *
     * @param idsArray
     * @return
     */
    @Log(title = "模型信息-批量删除", businessType = BusinessType.DELETE)
    @ApiOperation(value = "模型信息-批量删除", notes = "模型信息-批量删除")
    @RequiresPermissions("system:modelInfo:remove")
    @DeleteMapping(value = "/deleteBatch")
    public AjaxResult deleteBatch(@RequestParam(name = "idsArray", required = true) String[] idsArray) {
        for (int i = 0; i < idsArray.length; i++) {
            ModelInfo data = modelInfoService.getById(idsArray[i]);
            if(data == null){
                throw new ServiceException("删除模型信息不存在！");
            }
            if (0 == data.getIsDelete()){
                throw new ServiceException("当前模型已被删除！");
            }
            if (data != null) {
                data.setIsDelete(0);
                data.setUpdateStaffNo(SecurityUtils.getUserId());
                data.setUpdateTime(new Date());
                modelInfoService.updateById(data);
            }
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "模型信息-通过id查询", notes = "模型信息-通过id查询")
    @GetMapping(value = "/queryById")
    public AjaxResult queryById(@RequestParam(name = "id", required = true) String id) {
        ModelInfo modelInfo = modelInfoService.getById(id);
        if (modelInfo == null) {
            return AjaxResult.error("模型信息不存在");
        }
        return AjaxResult.success(modelInfo);
    }
    /**
     * 校验编号(已存在返回true)
     * @return
     */
    @GetMapping("/checkNumber")
    public AjaxResult checkNumber(String number, String modelName, String id){
        Boolean isExist = modelInfoService.checkNumber(number, modelName, id);
        return AjaxResult.success(isExist);
    }

}
